package com.bnzj.cloud.business.core.web;

import com.bnzj.cloud.business.core.persistence.entity.Group;
import com.bnzj.cloud.business.core.persistence.entity.SysSetting;
import com.bnzj.cloud.business.core.persistence.entity.SysUser;
import com.bnzj.cloud.business.core.service.GroupCourseService;
import com.bnzj.cloud.business.core.service.GroupService;
import com.bnzj.cloud.business.core.service.SysSettingService;
import com.bnzj.cloud.business.core.service.SysUserService;
import com.bnzj.core.action.ActionType;
import com.bnzj.core.action.annotation.Action;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.CurrentUserService;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.rest.UserInfo;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 富
 * @date 2020/5/9 9:24
 */
@Tag(name = "机构", description = "机构管理")
@RestController
@RequestMapping("/system/groups")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private GroupCourseService groupCourseService;

    @Autowired
    private CurrentUserService userService;

    @Autowired
    private SysUserService sysUserService;

    @Value("${bnzj.security.default-password?:987123}")
    private String defaultPassword;



    @PostMapping(value = "/list")
    public List<Group> getUserPage(){
        final List<Group> allGroup = groupService.findAllGroup();
        return allGroup;
    }


    @Operation(summary = "保存")
    @Action(descriprion = "机构保存",moduleName = "机构",operateType = ActionType.ADD_DATA)
    @PostMapping("/save")
    public ResponseResult<?> addGroup(@RequestBody Group group) {
        groupService.save(group);
        return ResponseResult.success();
    }

    @Operation(summary = "更新")
    @Action(descriprion = "机构更新",moduleName = "机构",operateType = ActionType.UPDATE_DATA)
    @PostMapping("/update")
    public ResponseResult<?> updateUser(@RequestBody Group group) {
        if (ObjectUtils.isEmpty(group.getId())) {
            throw new BusinessException("id不能为空！", ResultCode.BAD_REQUEST);
        }
        groupService.save(group);
        return ResponseResult.success();
    }


    @Operation(summary = "启动/禁用")
    @Action(descriprion = "机构启用禁用", moduleName = "机构", operateType = ActionType.UPDATE_DATA)
    @PostMapping("/job-level/enable/{id}")
    public ResponseResult<?> switchEnableState(@PathVariable("id") Long id) {
        UserInfo userInfo = userService.getUserInfo();
        groupService.switchEnableState(id, userInfo.getAccount(), userInfo.getName());
        return ResponseResult.success();
    }

    @Operation(summary = "分页查询")
    @GetMapping(value = "/page")
    public ResponseResult<Page<Group>> getSettingPage(HttpServletRequest request, @Parameter(description = "名称") @RequestParam(required = false) String name) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "modify_time"));
        QueryHelpBean bean = SysSettingService.getGroupHelpBean();
        bean.setPageable(pageable);
        //配置名称模糊搜索
        IExpression orCondition1 = CompareExpression.build("name", CompareType.like, name);
        bean.addWhere(orCondition1);
        Page<Group> all = groupService.findAll(bean);
        return ResponseResult.success(all);
    }

    @Operation(summary = "获取机构的用户信息")
    @PostMapping(value = "/findByGroupID")
    public ResponseResult<Page<SysUser>> findByGroupID(HttpServletRequest request, Long groupId, String typeUser) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "modify_time"));
        QueryHelpBean bean = SysSettingService.findAllByGroupId();
        bean.setPageable(pageable);
        String group = request.getParameter("groupId");
        if (ObjectUtils.isNotEmpty(group)) {
            IExpression orCondition1 = CompareExpression.build("bnz_sys_user.group_id", CompareType.equal, groupId);
            bean.addWhere(orCondition1);
        }
        IExpression orCondition2 = CompareExpression.build("bnz_sys_user.type", CompareType.equal, typeUser);
        bean.addWhere(orCondition2);

        Page<SysUser> all = groupService.findAll(bean);
        return ResponseResult.success(all);

    }

    @Operation(summary = "机构分配课程")
    @Action(descriprion = "机构分配课程",moduleName = "机构分配课程",operateType = ActionType.UPDATE_DATA)
    @PostMapping("/groupAssignCourse")
    public ResponseResult<?> groupAssignCourse(@RequestBody Map<String, String> map) {
        String groupId = map.get("groupId");
        String courseIds = map.get("courseIds");

        if (ObjectUtils.isEmpty(groupId)) {
            throw new BusinessException("机构id不能为空", ResultCode.BAD_REQUEST);
        }
        if (ObjectUtils.isEmpty(courseIds)) {
            throw new BusinessException("课程ids不能为空", ResultCode.BAD_REQUEST);
        }

        boolean res = groupCourseService.groupAssignCourse(groupId, courseIds);
        if(!res) {
            return ResponseResult.failure(0, "机构分配课程失败");
        }
        return ResponseResult.success();
    }

}
